import 'dart:async';
import 'package:flutter/material.dart';
import 'chat_emoji_view.dart';
import 'chat_model.dart';
import 'chat_viewmodel.dart';
import 'event_bus.dart';
import 'chat_type.dart';

class ChatInputBar extends StatefulWidget {
  final Function textHandle;
  const ChatInputBar({Key? key, required this.textHandle}) : super(key: key);

  @override
  ChatInputBarState createState() => ChatInputBarState();
}

class ChatInputBarState extends State<ChatInputBar>
    with WidgetsBindingObserver {
  final _focusNode = FocusNode();
  final _textController = TextEditingController();
  InputType _inputType = InputType.none;
  StreamSubscription? _stream;
  //标记输入文本的当前光标位置
  int _cursorIndex = 0;
  @override
  void initState() {
    super.initState();

    _stream = eventBus.on<EmojiModel>().listen((emojiModel) {
      //点击表情
      if (emojiModel.type == EmojiType.emoji) {
        int index = _cursorIndex;
        //光标左边
        String leftText = _textController.text.substring(0, index);
        //光标右边
        String rightText =
            _textController.text.substring(index, _textController.text.length);
        _textController.text = "$leftText${emojiModel.str}$rightText";

        _cursorIndex += emojiModel.str!.length;
      }

      //点击删除
      else if (emojiModel.type == EmojiType.delete) {
        if (_textController.text.isEmpty) return;

        int index = _cursorIndex;

        if (index <= 0) return;
        //判断左边字符串是否为表情
        int codeUnitAtIndex = _textController.text.codeUnitAt(index - 1);
        RegExp exp = RegExp(r"\[.{1,4}?\]");
        int deleteTotalCount = 1;
        //是表情符号
        if (_isUtf16Surrogate(codeUnitAtIndex)) {
          deleteTotalCount = 2;
        } else if (_textController.text.substring(index - 1, index) != "]") {
          deleteTotalCount = 1;
        }
        //是图片表情 表情最多3-6位【表情】
        else if (index >= 3 &&
            exp.hasMatch(_textController.text
                .substring(index >= 6 ? index - 6 : 0, index))) {
          Iterable<RegExpMatch> matches = exp.allMatches(_textController.text
              .substring(index >= 6 ? index - 6 : 0, index));
          int currentIndex = 0;
          //拿到最后一个
          for (var matche in matches) {
            if (currentIndex == matches.length - 1) {
              deleteTotalCount = matche.end - matche.start;
            }
            currentIndex++;
          }
        }

        String leftText =
            _textController.text.substring(0, index - deleteTotalCount);
        String rightText =
            _textController.text.substring(index, _textController.text.length);
        _textController.text = "$leftText$rightText";
        _cursorIndex -= deleteTotalCount;
      }
      //点击发送
      else if (emojiModel.type == EmojiType.send) {
        if (_textController.text.isEmpty) return;

        _cursorIndex = 0;
        widget.textHandle(_textController.text);
        _textController.text = "";
      }
    });

    //监听文本焦点
    _focusNode.addListener(() {
      //不在这里处理键盘弹起,拿不到键盘高度
      if (_focusNode.hasFocus) {
      } else {
        if (_inputType == InputType.input) {
          _inputType = InputType.none;
          setState(() {});
        }
      }
    });

    //监听键盘变化
    WidgetsBinding.instance?.addObserver(this);
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _stream?.cancel();

    WidgetsBinding.instance!.removeObserver(this);

    super.dispose();
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();

    if ((WidgetsBinding.instance?.window.viewInsets.bottom ?? 0.0) <= 0.0) {
      if (_inputType == InputType.input) {
        _focusNode.unfocus();
      }
    } else {
      //键盘弹出
      _inputType = InputType.input;
    }
  }

  hidenKeyBoard() {
    _focusNode.unfocus();
    _inputType = InputType.none;

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
            constraints: const BoxConstraints(maxHeight: 150),
            padding: const EdgeInsets.only(
              left: 10,
              top: 6,
              right: 6,
              bottom: 7,
            ),
            color: Colors.red,
            width: double.infinity,
            child: Row(
              children: [
                Flexible(
                    child: SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  //反向滚动，让内容从下到上
                  reverse: true,
                  child: TextField(
                    style: const TextStyle(
                      fontSize: 16,
                    ),
                    cursorColor: Colors.red,
                    controller: _textController,
                    focusNode: _focusNode,
                    textInputAction: TextInputAction.send,
                    maxLines: null,
                    keyboardType: TextInputType.text,
                    decoration: const InputDecoration(
                      //相当于不给大小,自己给文本大小
                      isCollapsed: true,
                      contentPadding: EdgeInsets.all(8),
                      // hintText: "请输入文字",
                      border: InputBorder.none, //去掉下划线
                      counterText: "", //去掉最大数量多少个显示
                      filled: true,
                      fillColor: Colors.white,
                    ),
                    onChanged: (value) {
                      _cursorIndex = _textController.selection.baseOffset;
                    },
                    onTap: () {
                      _cursorIndex = _textController.selection.baseOffset;
                    },
                    onSubmitted: (value) {
                      if (_textController.text.isEmpty) return;

                      _cursorIndex = 0;
                      widget.textHandle(value);
                      _textController.text = "";
                    },
                  ),
                )),
                const SizedBox(
                  width: 10,
                ),
                GestureDetector(
                  onTap: () {
                    //打开输入框
                    if (_inputType == InputType.emoj) {
                      _inputType = InputType.input;
                      _focusNode.requestFocus();
                    } else {
                      _focusNode.unfocus();
                      _inputType = InputType.emoj;

                      setState(() {});
                    }
                  },
                  child: const Icon(
                    Icons.emoji_emotions,
                    size: 32,
                  ),
                ),
                const SizedBox(
                  width: 5,
                ),
                GestureDetector(
                  onTap: () {
                    //打开输入框
                    if (_inputType == InputType.add) {
                      _focusNode.requestFocus();
                    }
                    //打开表情键盘
                    else {
                      _focusNode.unfocus();
                      _inputType = InputType.add;
                      setState(() {});
                    }
                  },
                  child: const Icon(
                    Icons.add,
                    size: 32,
                  ),
                ),
              ],
            )),
        SizedBox(
            height:
                (_inputType == InputType.emoj || _inputType == InputType.add)
                    ? 300
                    : _inputType == InputType.input
                        ? MediaQuery.of(context).viewInsets.bottom
                        : MediaQuery.of(context).padding.bottom,
            child: IndexedStack(
              index: _inputType == InputType.emoj
                  ? 1
                  : _inputType == InputType.add
                      ? 2
                      : 0,
              children: [
                Container(),
                const ChatEmojiView(),
                Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  color: Colors.yellow,
                  child: const Text("添加"),
                ),
              ],
            )),
      ],
    );
  }

  //是否为表情符合
  bool _isUtf16Surrogate(int value) {
    return (value & 0xF800) == 0xD800;
  }
}
